package com.lemon.smartsafetynew.ui.fragment.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.app.RefreshType;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.listener.HttpEventListener;
import com.lemon.smartsafety.listener.PullLoadMoreListener;
import com.lemon.smartsafety.listener.PullRefreshListener;
import com.lemon.smartsafety.utils.common.FileUtil;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.view.list.MultiStateView;
import com.lemon.smartsafetynew.util.common.MyIntent;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import kale.adapter.LemonRcvAdapter;
import okhttp3.Call;

/**
 * 项目名称：workspace
 * 类描述：
 * 创建人：Fargo
 * 创建时间：2016/7/13 13:37
 * 修改人：Fargo
 * 修改时间：2016/7/13 13:37
 * 修改备注：
 */
public abstract class BasePullToRefreshNoLoadMoreAddTitleFragment<L, H extends List> extends BaseFragment implements HttpEventListener<H>, PullRefreshListener, PullLoadMoreListener {
    @Bind(R.id.tv_title)
    public TextView tvTitle;
    @Bind(R.id.tv_title_count)
    public TextView tvTitleCount;
    @Bind(R.id.ll_tilte)
    public LinearLayout llTilte;
    @Bind(R.id.tv_record_title)
    public TextView tvRecordTitle;
    @Bind(R.id.ll_yellow_title)
    public LinearLayout llYellowTitle;
    private LoggerHelper loggerHelper = new LoggerHelper(BasePullToRefreshFragment.class);

    @Bind(R.id.pullToRefreshRecyclerView)
    public PullToRefreshRecyclerView mPullToRefreshRecyclerView;

    @Nullable
    @Bind(R.id.multiStateView)
    public MultiStateView mMultiStateView;


    @Nullable
    @Bind(R.id.top_line)
    protected View mTopLine;


    @Nullable
    @Bind(R.id.float_button)
    protected FloatingActionButton fab;

    protected int currentPage = Constants.DEFAULT_FIRST_PAGE_NUMBER;

    protected int pageSize = Constants.PAGE_SIZE;

    public H mDataList = (H) new ArrayList<>();

    protected LemonRcvAdapter<L> mAdapter;

    @Override
    protected void initViews() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(IApplication.context(), LinearLayoutManager.VERTICAL, false);
        mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
        mPullToRefreshRecyclerView.setLayoutManager(layoutManager);
        mAdapter = getLemonAdapter();
        mPullToRefreshRecyclerView.setAdapter(mAdapter);
        mPullToRefreshRecyclerView.setOnPullUpToRefreshListener(new PullToRefreshRecyclerView.OnPullUpToRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = Constants.DEFAULT_FIRST_PAGE_NUMBER;
                onPullRefresh();
            }
        });
        mPullToRefreshRecyclerView.setOnPullDownToRefreshListener(new PullToRefreshRecyclerView.OnPullDownToRefreshListener() {
            @Override
            public void onRefresh() {
                onLoadMore();
            }
        });

        mMultiStateView.setErrorRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                mPullToRefreshRecyclerView.beginRefreshing();
            }
        });
    }

    public void doPullRefresh() {
        mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
        mPullToRefreshRecyclerView.beginRefreshing();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (goRefreshOnCreate()) {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            mPullToRefreshRecyclerView.beginRefreshing();
        }
    }

    //刷新标题数目
    public abstract void onDataList(H data);

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_refresh_title;
    }

    @Override
    protected void getBaseArguments() {

    }

    /**
     * 是否在视图创建好后，就自动下来刷新
     *
     * @return
     */
    public abstract boolean goRefreshOnCreate();


    /**
     * 设置页面的Adapter
     *
     * @return
     */
    public abstract LemonRcvAdapter<L> getLemonAdapter();

    /**
     * 给请求设置一个Tag 可以过滤OnEvent的处理
     *
     * @return
     */
    public abstract String getHttpTag();


    /**
     * 数据请求事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent<H> event) {
        if (!getHttpTag().equals(event.getTag())) {
            return;
        }
        if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
        } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow() && mPullToRefreshRecyclerView != null) {
            RefreshType type = (RefreshType) event.getOther();
            if (RefreshType.REFRESH == type) {
                mPullToRefreshRecyclerView.onRefreshComplete();
            } else {
                mPullToRefreshRecyclerView.setFooterComplete();
            }
            if (Constants.Result.SUCCESS == event.getEventResult()) {
                if (RefreshType.REFRESH == type) {
                    httpRefresh(event.getObj());
                } else {
                    httpLoadMore(event.getObj());
                }
                currentPage++;
            } else if (Constants.Result.ERROR == event.getEventResult()) {
                if (RefreshType.REFRESH == type) {
                    httpRefreshError(event.getMsg());
                } else {
                    httpLoadMoreError(event.getMsg());
                }
            }

            //            mPullToRefreshRecyclerView.setFooterRetryListener(new View.OnClickListener() {
            //                @Override
            //                public void onClick(View v) {
            //                    loggerHelper.w("retry");
            //                }
            //            });
        }
    }


    @Override
    public void httpRefresh(H data) {
        onDataList(data);
        if (data != null && !data.isEmpty()) {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            if (data.size() < pageSize) {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
                //mPullToRefreshRecyclerView.setFooterComplete();
            } else {
                //mPullToRefreshRecyclerView.setRefreshMode(Mode.BOTH);
            }
            mDataList.clear();
            mAdapter.notifyDataSetChanged();
            mAdapter.addItems(data);
        } else {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
        }
    }

    @Override
    public void httpLoadMore(H data) {
        if (data != null && !data.isEmpty()) {
            if (data.size() < pageSize) {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
                mPullToRefreshRecyclerView.setFooterComplete();
            } else {
                //mPullToRefreshRecyclerView.setRefreshMode(Mode.BOTH);
            }
            mAdapter.addItems(data);
        }
    }

    @Override
    public void httpRefreshError(String msg) {
        mHUDUtil.showErrorTip(msg);
        mMultiStateView.setErrorTip(msg);
    }

    @Override
    public void httpLoadMoreError(String msg) {
        //mHUDUtil.showErrorTip(msg);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    //文件展示
    public void downloadAndShowFile(String urls, String names, Context context, String modeNmae) {
        String fielname="";
        try {
            if(!TextUtils.isEmpty(urls)){
                String url[] = urls.split("/");
                if(!TextUtils.isEmpty(names) && url.length > 0){
                    String name[] = names.split("\\.");
                    fielname = modeNmae+"_"+name[0]+"_"+url[url.length-1];
                }else{
                    fielname = modeNmae+"_"+"附件"+"_"+url[url.length-1];
                }
                File file = new File(FileUtil.getAppOneComOneDocDir(context)+ File.separator + fielname);
                if(!file.exists()) {
                    getFile(urls, fielname,context);
                }else{
                    showFiles(fielname,file,context);
                }
            }else{
                mHUDUtil.showErrorTip("该文件地址有误!");
            }
        }catch (Exception e){
            mHUDUtil.showErrorTip("该文件地址有误!");
        }
    }

    private void getFile(String fileUrl, final String fileName, final Context contxt) {
        mHUDUtil.showHUD();
        OkHttpUtils
                .get()
                .url(fileUrl)
                .build()
                .execute(new FileCallBack(FileUtil.getAppOneComOneDocDir(contxt), fileName) {
                    @Override
                    public void onError(Call call, Exception e) {
                        mHUDUtil.showErrorTip("获取文件失败。");
                    }

                    @Override
                    public void onResponse(File response) {
                        showFiles(fileName,response,contxt);
                    }

                    @Override
                    public void inProgress(float progress, long total) {
                        if(progress == 1.0){
                            mHUDUtil.hidden();
                        }
                    }
                });
    }

    //文件的预览
    private void showFiles(String fileName, File response,Context context) {
        Intent intent = null;
        if (fileName.endsWith(".xlsx") || fileName.endsWith(".xls")
                || fileName.endsWith(".XLSX") || fileName.endsWith(".XLS")){
            intent = MyIntent.getExcelFileIntent(response.getPath());
        } else if(fileName.endsWith(".txt") || fileName.endsWith(".TXT")){
            intent = MyIntent.getTextFileIntent(response.getPath(),false);
        } else if(fileName.endsWith(".doc") || fileName.endsWith(".docx")
                || fileName.endsWith(".DOC") || fileName.endsWith(".DOCX")){
            intent = MyIntent.getWordFileIntent(response.getPath());
        } else if(fileName.endsWith(".ppt") || fileName.endsWith(".PPT")
                || fileName.endsWith(".pptx") || fileName.endsWith(".PPTX") ){
            intent = MyIntent.getPptFileIntent(response.getPath());
        } else if(fileName.endsWith(".pdf") || fileName.endsWith(".PDF")){
            intent = MyIntent.getPdfFileIntent(response.getPath());
        } else if(fileName.endsWith(".png") || fileName.endsWith(".PNG")
                || fileName.endsWith(".jpg") || fileName.endsWith(".JPG")
                || fileName.endsWith(".jpeg") || fileName.endsWith(".JPEG")){
            intent = MyIntent.getImageFileIntent(response.getPath());
        } else if(fileName.endsWith(".mp4") || fileName.endsWith(".MP4")){
            intent = MyIntent.getVideoFileIntent(response.getPath());
        } else if(fileName.endsWith(".wma") || fileName.endsWith(".wav") || fileName.endsWith(".mp3") ){
            intent = MyIntent.getAudioFileIntent(response.getPath());
        } else {
            intent = null;
        }

        try {
            if(intent != null) {
                context.startActivity(intent);
            } else {
                mHUDUtil.showErrorTip("未能识别此类文件！");
            }
        } catch (Exception e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mHUDUtil.showErrorTip("没有相应工具打开此类文件，请下载相关App查看此类文件！");
                }
            });
        }
    }
}
